/**
 * 进入编辑文章页面路由
 * 进入发布文章页面路由
 * 进入转载文章页面路由
 */

var router = require('express').Router();
var userTool = require('../bin/user');
var articleTool = require('../bin/article');
var blockTool = require('../bin/block');
var assertAlljs = require('../bin/util/assert-alljs');
var articleConvention = require('../convention/article_convention');
var dbentityTool = require('../bin/dbentity');
var ObjectID = require('mongodb').ObjectID;
var datetimeTool = require('../bin/util/datetime');

router.get('/articledit(.*)?', async function(req, res) {
    let user = req.session.user;
    let assert = assertAlljs(req, res);
    if (await assert(userTool.check(user)))
        return;

    if (await assert(typeof(req.query.id) !== 'string' || req.query.id === '', '缺少请求参数'))
        return;

    let doc = await dbentityTool.findOne('article', {_id:ObjectID(req.query.id)});
    if (await assert(doc instanceof Error))
        return;

    let article = doc;
    article._id = article._id.toString();

    if (await assert(
        (user.role !== 'admin')
        && (user._id !== article.produceUser._id || (new Date().getTime() -  article.produceTime) > 30 * 3600 * 1000),
        '已超过30小时可编辑时间'))
        return;

    let local = articleTool.toLocalFull(article);
    if (typeof(local.publish) === 'number')
        local.publish =  datetimeTool.to_yMdHm(local.publish,'-', 'T');

    res.locals.descendantBlocks = blockTool.getDescendantBlocks(res.locals.blocks, res.locals.block);
    res.locals.blocksDic = blockTool.getBlocksDic(res.locals.blocks, true);
    local.edit = true;
    local.reproduce = false;
    res.render('dyn.articledit.html', local);
});

router.get('/articlepublic(.*)?', async function(req, res) {
    let user = req.session.user;
    let assert = assertAlljs(req, res);
    if (await assert(userTool.check(user)))
        return;

    let local = {};
    for (let key in articleConvention){
        if (key !== undefined)
            local[key] = '';
    }

    res.locals.descendantBlocks = blockTool.getDescendantBlocks(res.locals.blocks, res.locals.block);
    res.locals.blocksDic = blockTool.getBlocksDic(res.locals.blocks, true);
    local.edit = false;
    local.reproduce = false;

    res.render('dyn.articledit.html', local);
});

router.get('/articlereproduce(.*)?', async function(req, res) {
    let user = req.session.user;
    let assert = assertAlljs(req, res);
    if (await assert(userTool.check(user)))
        return;

    let local = {};
    for (let key in articleConvention){
        if (key !== undefined)
            local[key] = '';
    }

    res.locals.descendantBlocks = blockTool.getDescendantBlocks(res.locals.blocks, res.locals.block);
    res.locals.blocksDic = blockTool.getBlocksDic(res.locals.blocks, true);
    local.edit = false;
    local.reproduce = true;

    res.render('dyn.articledit.html', local);
});

module.exports = router;